package com.minsf.springbootinit.classLoaderTest;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @Description
 * @Author minify
 * @Date 2024/2/17 15:02
 * @Project oj-backend
 */
public class MyClassLoader extends ClassLoader {

    private String byteCodePath;

    public MyClassLoader(ClassLoader parent, String byteCodePath) {
        super(parent);
        this.byteCodePath = byteCodePath;
    }

    public MyClassLoader(String byteCodePath) {
        this.byteCodePath = byteCodePath;
    }

    @Override
    protected Class<?> findClass(String name) {

        BufferedInputStream bis = null;
        ByteArrayOutputStream bos = null;
        InputStream systemResourceAsStream = null;

        try {
            String classPath = byteCodePath + name + ".class";
            systemResourceAsStream = ClassLoader.getSystemResourceAsStream(name);
            bis = new BufferedInputStream(systemResourceAsStream);
            bos = new ByteArrayOutputStream();

            int len;
            byte[] data = new byte[1024];
            while ((len = bis.read(data)) != -1) {
                bos.write(data, 0, len);
            }
            byte[] byteArray = bos.toByteArray();
            defineClass(null, byteArray, 0, byteArray.length);

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (bis != null)
                    bis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            if (systemResourceAsStream != null) {
                try {
                    systemResourceAsStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            try {
                if (bos != null)
                    bos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return null;
    }
}
